package com.newfiber.system.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.newfiber.business.api.RemoteDocumentService;
import com.newfiber.common.core.domain.R;
import com.newfiber.common.core.exception.ServiceException;
import com.newfiber.common.core.utils.file.FileUtils;
import com.newfiber.common.core.web.domain.BaseEntity;
import com.newfiber.common.core.web.service.BaseServiceImpl;
import com.newfiber.system.api.domain.SysFile;
import com.newfiber.system.api.domain.request.SysFileSaveRequest;
import com.newfiber.system.domain.request.sysFile.SysFileQueryRequest;
import com.newfiber.system.mapper.SysFileMapper;
import com.newfiber.system.service.ISysFileService;
import com.newfiber.system.service.ISysFileUploadService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件Service业务层处理
 *
 * @author X.K
 * @date 2023-02-22
 */
@Service
public class SysFileServiceImpl extends BaseServiceImpl<SysFileMapper, SysFile> implements ISysFileService {

    @Resource
    private SysFileMapper sysFileMapper;

    @Resource
    private ISysFileUploadService sysFileUploadService;

    @Resource
    private RemoteDocumentService remoteDocumentService;

    @Override
    public R<SysFile> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileUploadService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setOriginalName(file.getOriginalFilename());
            sysFile.setUrl(url);
            sysFile.setExtension(FileUtil.getSuffix(sysFile.getOriginalName()));
            sysFile.setSize(file.getSize());
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @Override
    public SysFile uploadRef(String refType, String refField, Long refId, String remark, MultipartFile file) {
        try {
            String url = sysFileUploadService.uploadFile(file);

            SysFile sysFile = new SysFile();
            sysFile.setRefType(refType);
            sysFile.setRefField(refField);
            sysFile.setRefId(refId);
            sysFile.setName(file.getName());
            sysFile.setOriginalName(file.getOriginalFilename());
            sysFile.setUrl(url);
            sysFile.setExtension(FileUtil.getSuffix(sysFile.getOriginalName()));
            sysFile.setSize(file.getSize());

            save(sysFile);
            return sysFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(String.format("文件上传失败:{%s", e.getMessage()));
        }
    }

    @Override
    public long insert(Long refId, SysFileSaveRequest request) {
        SysFile sysFile = new SysFile();
        BeanUtils.copyProperties(request, sysFile);
        sysFile.setRefId(refId);
        save(sysFile);
        return Optional.of(sysFile).map(BaseEntity::getId).orElse(0L);
    }

    @Override
    public boolean insert(String refType, Long refId, List<SysFileSaveRequest> request) {
        if (CollectionUtils.isEmpty(request)) {
            return true;
        }
        String refField = "";
        List<SysFile> sysFileList = new ArrayList<>();
        for (SysFileSaveRequest saveRequest : request) {
            SysFile sysFile = new SysFile();
            BeanUtils.copyProperties(saveRequest, sysFile);
            if (StringUtils.isNotBlank(refType)) {
                sysFile.setRefType(refType);
            }
            sysFile.setRefId(refId);
            sysFileList.add(sysFile);
            refField = saveRequest.getRefField();
        }
        remoteDocumentService.saveDocumentFiles(refType,refField,refId);

        return saveBatch(sysFileList, sysFileList.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        return deleteLogic(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(String refType, Long refId, List<SysFileSaveRequest> request) {
        SysFileQueryRequest queryRequest = new SysFileQueryRequest();
        queryRequest.setRefType(refType);
        queryRequest.setRefId(refId);
        List<SysFile> sysFiles = sysFileMapper.selectByCondition(queryRequest);
        if (CollectionUtils.isNotEmpty(sysFiles)) {
            List<String> idList = new ArrayList<>();
            sysFiles.forEach(e -> {
                idList.add(e.getId().toString());
            });
            delete(String.join(",", idList));
        }
        return insert(refType, refId, request);
    }

    @Override
    public SysFile selectDetail(Long id) {
        SysFile sysFile = sysFileMapper.selectById(id);
        if (null == sysFile) {
            throw new ServiceException(String.format("%s ID=%s 的记录不存在", this.getClass().getSimpleName(), id));
        }
        return sysFile;
    }

    @Override
    public List<SysFile> selectPage(SysFileQueryRequest request) {
        return sysFileMapper.selectByCondition(request);
    }

    @Override
    public List<SysFile> selectList(SysFileQueryRequest request) {
        return sysFileMapper.selectByCondition(request);
    }

    @Override
    public List<SysFile> selectList(Long refId) {
        SysFileQueryRequest request = new SysFileQueryRequest();
        request.setRefId(refId);
        return sysFileMapper.selectByCondition(request);
    }

    @Override
    public List<SysFile> selectByRefIds(String refIds) {
        return this.list(Wrappers.lambdaQuery(SysFile.class).in(SysFile::getRefId,refIds.split(",")).eq(SysFile::getDelFlag,0));
    }
}
